/**
 * 二分查找
 */
public class Solution {
  public int search(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;
    while (left <= right) {
      int mid = (left + right) >> 1;
      // System.out.println("left:" + left + " right:" + right + " mid:" + nums[mid]);
      if (nums[mid] < target) {
        left = mid + 1;
      } else if (nums[mid] > target) {
        right = mid - 1;
      } else {
        // 因为数组中等于的情况比较少，所以将相等放到最后判断
        return mid;
      }
    }
    return -1;
  }

  public static void main(String[] args) {
    int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int res = new Solution().search(nums, 7);
    System.out.println(res);
  }
}
